package com.warom.sdg.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.model.OperationLogEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 操作日志数据访问对象实现类
 */
public class OperationLogDao_Impl implements OperationLogDao {
    private static final String TAG = "OperationLogDao_Impl";
    
    private final SdgDatabase database;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    
    public OperationLogDao_Impl(SdgDatabase database) {
        this.database = database;
    }
    
    @Override
    public long insert(OperationLogEntity log) {
        SQLiteDatabase db = database.getWritableDatabase();
        ContentValues values = new ContentValues();
        
        values.put(SdgDatabase.COLUMN_OPERATION_USERNAME, log.getUsername());
        values.put(SdgDatabase.COLUMN_OPERATION_TYPE, log.getOperationType());
        values.put(SdgDatabase.COLUMN_OPERATION_DESCRIPTION, log.getOperationDescription());
        values.put(SdgDatabase.COLUMN_OPERATION_PAGE, log.getOperationPage());
        values.put(SdgDatabase.COLUMN_OPERATION_TARGET, log.getOperationTarget());
        values.put(SdgDatabase.COLUMN_OPERATION_STATUS, log.getOperationStatus());
        values.put(SdgDatabase.COLUMN_OPERATION_ERROR_MESSAGE, log.getErrorMessage());
        values.put(SdgDatabase.COLUMN_OPERATION_TIME, log.getOperationTime());
        values.put(SdgDatabase.COLUMN_OPERATION_TIME_STRING, 
                   log.getOperationTimeString() != null ? log.getOperationTimeString() : 
                   dateFormat.format(new Date(log.getOperationTime())));
        values.put(SdgDatabase.COLUMN_OPERATION_IP_ADDRESS, log.getIpAddress());
        values.put(SdgDatabase.COLUMN_OPERATION_USER_AGENT, log.getUserAgent());
        
        long id = db.insert(SdgDatabase.TABLE_OPERATION_LOGS, null, values);
        Log.d(TAG, "插入操作日志成功，ID: " + id);
        return id;
    }
    
    @Override
    public int insertBatch(List<OperationLogEntity> logs) {
        return 0;
    }
    
    @Override
    public void deleteById(long id) {
        SQLiteDatabase db = database.getWritableDatabase();
        db.delete(
                SdgDatabase.TABLE_OPERATION_LOGS,
                SdgDatabase.COLUMN_ID + " = ?",
                new String[]{String.valueOf(id)}
        );
    }
    
    @Override
    public void deleteByTimeRange(long startTime, long endTime) {
        SQLiteDatabase db = database.getWritableDatabase();
        db.delete(
                SdgDatabase.TABLE_OPERATION_LOGS,
                SdgDatabase.COLUMN_OPERATION_TIME + " >= ? AND " + SdgDatabase.COLUMN_OPERATION_TIME + " <= ?",
                new String[]{String.valueOf(startTime), String.valueOf(endTime)}
        );
    }
    
    @Override
    public int deleteLogsBefore(long timestamp) {
        SQLiteDatabase db = database.getWritableDatabase();
        return db.delete(
                SdgDatabase.TABLE_OPERATION_LOGS,
                SdgDatabase.COLUMN_OPERATION_TIME + " < ?",
                new String[]{String.valueOf(timestamp)}
        );
    }
    
    @Override
    public List<OperationLogEntity> getAllLogs() {
        List<OperationLogEntity> logs = new ArrayList<>();
        SQLiteDatabase db = database.getReadableDatabase();
        
        Cursor cursor = db.query(
                SdgDatabase.TABLE_OPERATION_LOGS,
                null,
                null,
                null,
                null,
                null,
                SdgDatabase.COLUMN_OPERATION_TIME + " DESC"
        );
        
        try {
            if (cursor.moveToFirst()) {
                do {
                    logs.add(cursorToEntity(cursor));
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
        }
        
        return logs;
    }
    
    @Override
    public List<OperationLogEntity> getLogsByUsername(String username) {
        List<OperationLogEntity> logs = new ArrayList<>();
        SQLiteDatabase db = database.getReadableDatabase();
        
        Cursor cursor = db.query(
                SdgDatabase.TABLE_OPERATION_LOGS,
                null,
                SdgDatabase.COLUMN_OPERATION_USERNAME + " = ?",
                new String[]{username},
                null,
                null,
                SdgDatabase.COLUMN_OPERATION_TIME + " DESC"
        );
        
        try {
            if (cursor.moveToFirst()) {
                do {
                    logs.add(cursorToEntity(cursor));
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
        }
        
        return logs;
    }
    
    @Override
    public List<OperationLogEntity> getLogsByOperationType(String operationType) {
        return new ArrayList<>();
    }
    
    @Override
    public List<OperationLogEntity> getLogsByOperationPage(String operationPage) {
        return new ArrayList<>();
    }
    
    @Override
    public List<OperationLogEntity> getLogsByOperationStatus(String operationStatus) {
        return new ArrayList<>();
    }
    
    @Override
    public List<OperationLogEntity> getLogsByTimeRange(long startTime, long endTime) {
        return new ArrayList<>();
    }
    
    @Override
    public List<OperationLogEntity> getLogsPaginated(int offset, int limit) {
        List<OperationLogEntity> logs = new ArrayList<>();
        SQLiteDatabase db = database.getReadableDatabase();
        
        Cursor cursor = db.query(
                SdgDatabase.TABLE_OPERATION_LOGS,
                null,
                null,
                null,
                null,
                null,
                SdgDatabase.COLUMN_OPERATION_TIME + " DESC",
                offset + "," + limit
        );
        
        try {
            if (cursor.moveToFirst()) {
                do {
                    logs.add(cursorToEntity(cursor));
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
        }
        
        return logs;
    }
    
    @Override
    public List<OperationLogEntity> getLogsByConditionsPaginated(
            String username, String operationType, String operationPage, 
            String operationStatus, long startTime, long endTime, 
            int offset, int limit) {
        return new ArrayList<>();
    }
    
    @Override
    public int getLogCount() {
        SQLiteDatabase db = database.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + SdgDatabase.TABLE_OPERATION_LOGS, null);
        
        int count = 0;
        try {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } finally {
            cursor.close();
        }
        
        return count;
    }
    
    @Override
    public int getLogCountByConditions(
            String username, String operationType, String operationPage, 
            String operationStatus, long startTime, long endTime) {
        return 0;
    }
    
    @Override
    public int deleteAllLogs() {
        SQLiteDatabase db = database.getWritableDatabase();
        return db.delete(
                SdgDatabase.TABLE_OPERATION_LOGS,
                null,
                null
        );
    }
    
    @Override
    public int getLogCountSince(long timestamp) {
        SQLiteDatabase db = database.getReadableDatabase();
        
        Cursor cursor = db.rawQuery(
                "SELECT COUNT(*) FROM " + SdgDatabase.TABLE_OPERATION_LOGS + 
                " WHERE " + SdgDatabase.COLUMN_OPERATION_TIME + " >= ?",
                new String[]{String.valueOf(timestamp)}
        );
        
        int count = 0;
        try {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } finally {
            cursor.close();
        }
        
        return count;
    }
    
    @Override
    public int getLogCountByStatus(String status) {
        SQLiteDatabase db = database.getReadableDatabase();
        
        Cursor cursor = db.rawQuery(
                "SELECT COUNT(*) FROM " + SdgDatabase.TABLE_OPERATION_LOGS + 
                " WHERE " + SdgDatabase.COLUMN_OPERATION_STATUS + " = ?",
                new String[]{status}
        );
        
        int count = 0;
        try {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } finally {
            cursor.close();
        }
        
        return count;
    }
    
    /**
     * 将查询结果转换为实体对象
     */
    private OperationLogEntity cursorToEntity(Cursor cursor) {
        OperationLogEntity entity = new OperationLogEntity();
        
        int idIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_ID);
        if (idIndex != -1) {
            entity.setId(cursor.getLong(idIndex));
        }
        
        int usernameIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_USERNAME);
        if (usernameIndex != -1) {
            entity.setUsername(cursor.getString(usernameIndex));
        }
        
        int typeIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_TYPE);
        if (typeIndex != -1) {
            entity.setOperationType(cursor.getString(typeIndex));
        }
        
        int descIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_DESCRIPTION);
        if (descIndex != -1) {
            entity.setOperationDescription(cursor.getString(descIndex));
        }
        
        int pageIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_PAGE);
        if (pageIndex != -1) {
            entity.setOperationPage(cursor.getString(pageIndex));
        }
        
        int targetIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_TARGET);
        if (targetIndex != -1) {
            entity.setOperationTarget(cursor.getString(targetIndex));
        }
        
        int statusIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_STATUS);
        if (statusIndex != -1) {
            entity.setOperationStatus(cursor.getString(statusIndex));
        }
        
        int errorIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_ERROR_MESSAGE);
        if (errorIndex != -1) {
            entity.setErrorMessage(cursor.getString(errorIndex));
        }
        
        int timeIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_TIME);
        if (timeIndex != -1) {
            entity.setOperationTime(cursor.getLong(timeIndex));
        }
        
        int timeStringIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_TIME_STRING);
        if (timeStringIndex != -1) {
            entity.setOperationTimeString(cursor.getString(timeStringIndex));
        }
        
        int ipIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_IP_ADDRESS);
        if (ipIndex != -1) {
            entity.setIpAddress(cursor.getString(ipIndex));
        }
        
        int userAgentIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_OPERATION_USER_AGENT);
        if (userAgentIndex != -1) {
            entity.setUserAgent(cursor.getString(userAgentIndex));
        }
        
        return entity;
    }
} 